<?php

namespace App\Common\Http\Controller;

use App\ApiBaseController;
use AlibabaCloud\Client\AlibabaCloud;
use AlibabaCloud\Client\Exception\ClientException;
use AlibabaCloud\Client\Exception\ServerException;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;

class StsController extends ApiBaseController
{
    /**
     * User: zhangchaoqun
     * DateTime: 2021/6/16 1:36 下午
     * Describe: STS加密阿里云OSS秘钥
     * Version: V1.0
     * @return \Illuminate\Http\JsonResponse
     * @throws ClientException
     */
    public function aliOss()
    {
        AlibabaCloud::accessKeyClient('LTAI5t7a9UoUk8HSMaNG7guS', 's9sWqWBozLff6l27EexkVnI1dvAT2p')
            ->regionId('cn-hangzhou')
            ->asDefaultClient();

        try {
            $result = AlibabaCloud::rpc()
                ->product('Sts')
                ->version('2015-04-01')
                ->action('AssumeRole')
                ->method('POST')
                ->scheme('https')
                ->host('sts.aliyuncs.com')
                ->options([
                    'query' => [
                        'RegionId' => 'cn-zhangzhou',
                        'RoleArn' => 'acs:ram::1038315518746094:role/aliyunosstokengeneratorrole',
                        'RoleSessionName' => 'external-username',
                    ]
                ])
                ->request();

            $data = [
                'credentials' => $result->toArray()['Credentials'],
                'path' => 'im/images/'.date('Y/m/d') . '/'
            ];

            return $this->success('获取成功', $data);
        } catch (ClientException $exception) {
            return $this->error($exception->getErrorMessage());
        } catch (ServerException $exception) {
            return $this->error($exception->getErrorMessage());
        }
    }
}
